/**
 * Created by lenovo on 2017/8/31.
 */

var myApp = new Framework7({
    init: false,
    modalTitle: '提示',
    modalButtonOk: '确认',
    modalButtonCancel: '取消',
    pushState: true,
    swipeBackPage: false,
    uniqueHistory: true,
    showBarsOnPageScrollEnd: false,
    activeStateElemets: 'a, button',
    onAjaxStart: function (xhr) {
        myApp.showIndicator();
    },
    onAjaxComplete: function (xhr) {
        myApp.hideIndicator();
    }
});
const CND_URL = 'http://cdn.bestmovie.com.cn';
Template7.registerHelper('jsonDecodeNumbers', function (s) {
    return JSON.parse(s).numbers;
});
Template7.registerHelper('jsonDecodeContact', function (s) {
    return JSON.parse(s).bookingContact;
});
Template7.registerHelper('jsonDecodeComment', function (s) {
    return JSON.parse(s).userComment;
});
Template7.registerHelper('formatChineseWeek', function (w) {
    var cWeek = '';
    if (w == 1) {
        cWeek = '周日';
    } else if (w == 2) {
        cWeek = '周一';
    } else if (w == 3) {
        cWeek = '周二';
    } else if (w == 4) {
        cWeek = '周三';
    } else if (w == 5) {
        cWeek = '周四';
    } else if (w == 6) {
        cWeek = '周五';
    } else {
        cWeek = '周六';
    }
    return cWeek;
});
Template7.registerHelper('formatPrice', function (money) {
    if (money == "") {
        return "";
    }
    if (money) {
        money = parseInt(money) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(money)) {
        return '¥' + money + '/小时';
    }
    money = parseFloat(money) + "";
    if ('NaN' == money) {
        return '未设定';
    }
    var money_flag = "";
    if (money.indexOf("-") != -1) {
        money = money.replace(/-/g, "");
        money_flag = "-";
    }
    money = money.replace(/^(\d*)$/, "$1.");
    money = (money + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    money = money.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(money)) {
        money = money.replace(re, "$1,$2");
    }
    money = money.replace(/,(\d\d)$/, ".$1");
    var money = money_flag + "¥" + money.replace(/^\./, "0.") + '/小时';
    return money;
});
Template7.registerHelper('formatPerCapita',function (price) {
    if (price == "") {
        return "";
    }
    if (price) {
        price = parseInt(price) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(price)) {
        price = price.toFixed(2);
        return '¥' + price + '/人';
    } else {
        return '¥' + price + '/人';
    }
});
Template7.registerHelper('formatConsumption', function (money) {
    if (money == "") {
        return "";
    }
    if (money) {
        money = parseInt(money) * 0.01;
    }
    if (/[^0-9\.\-\+]/.test(money)) {
        return money;
    }
    money = parseFloat(money) + "";
    if ('NaN' == money) {
        return "";
    }
    var money_flag = "";
    if (money.indexOf("-") != -1) {
        money = money.replace(/-/g, "");
        money_flag = "-";
    }
    money = money.replace(/^(\d*)$/, "$1.");
    money = (money + "00").replace(/(\d*\.\d\d)\d*/, "$1");
    money = money.replace(".", ",");
    var re = /(\d)(\d{3},)/;
    while (re.test(money)) {
        money = money.replace(re, "$1,$2");
    }
    money = money.replace(/,(\d\d)$/, ".$1");
    var money = money_flag + "" + money.replace(/^\./, "0.")
    return '￥' + money + '/人';
});
Template7.registerHelper('formatDistance', function (distance) {
    distance = Math.sqrt(distance)*100*1000;
    if (distance < 1000) {
        distance = Math.round(distance)+"m";
    } else if (distance > 1000 && distance < 100000) {
        var jl = distance / 1000.0;
        distance = jl.toFixed(1) + "km";
    } else {
        distance = ">100km";
    }
    return distance;
});
Template7.registerHelper('CND', function (url) {
    const c = 'http://cdn.bestmovie.com.cn/'
    return c + url;
});
Template7.registerHelper('ALBUM_POSTER', function (album_id, wx_poster) {
    return CND_URL + '/ALBUM/' + album_id + '/' + wx_poster;
});
Template7.registerHelper('CINEMA_BANNER_POSTER', function (banner_poster) {
    return CND_URL + '/' + banner_poster;
});
Template7.registerHelper('MOVIE_BANNER_POSTER', function (banner_poster) {
    return CND_URL + '/' + banner_poster;
});
Template7.registerHelper('MOVIE_POSTER', function (mid, poster) {
    return CND_URL + '/MOVIE/' + mid + '/POSTER/' + poster;
});
Template7.registerHelper('CINEMA_POSTER', function (cinema_code, poster) {
    var a = poster.split('/');
    if (a.length>1){
        var p = a[a.length-1];
        return require('./config').cdn.imgs + '/' +cinema_code + '/pic/'+ p;
    }else {
        return require('./config').cdn.imgs + '/' +cinema_code + '/pic/'+ cinema_code + '.jpg';
    }
});
Template7.registerHelper('formatMovieScore', function (score) {
    var t = score.toFixed(0);
    if (t == score){
        return score + '.0';
    } else {
        return score;
    }
});
Template7.registerHelper('formatDoughnut', function (score) {
    var tmp = '';
    if ( score >= 9.5) {
        tmp = "./img/010-wx-score.png";
    } else if (8.5 <= score && score< 9.5) {
        tmp = "./img/009-wx-score.png";
    } else if (7.5 <= score && score< 8.5) {
        tmp = "./img/008-wx-score.png";
    } else if (6.5 <= score && score< 7.5) {
        tmp = "./img/007-wx-score.png";
    } else if (5.5 <= score && score< 6.5) {
        tmp = "./img/006-wx-score.png";
    } else if (4.5 <= score && score< 5.5) {
        tmp = "./img/005-wx-score.png";
    } else if (3.5 <= score && score< 4.5) {
        tmp = "./img/004-wx-score.png";
    } else if (2.5 <= score && score< 3.5) {
        tmp = "./img/003-wx-score.png";
    } else {
        tmp = "./img/002-wx-score.png";
    }
    return tmp;
});

var $$ = Dom7;
var mainView = myApp.addView('.view-main',
    {domCache: true});

var Convert_BD09_To_GCJ02 = function(point) {
    const x_pi= 3.14159265358979324 * 3000.0 / 180.0;
    var x = point.lng - 0.0065, y = point.lat - 0.006;
    var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
    var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
    point.lng = z * Math.cos(theta);
    point.lat = z * Math.sin(theta);
};
var latitude = 0.01;
var longitude = 0.01;
var getCurrentLocation = function (success,failure) {
    // wx.ready(function(){
    //     wx.getLocation({
    //         type: 'wgs84',
    //         success: function (res) {
    //             success(res.latitude,res.longitude);
    //         },
    //         fail:function (res) {
    //             failure(res);
    //         },
    //         cancel: function (res) {
    //             failure(res);
    //         }
    //     });
    // });
    // var mapObj = new AMap.Map('iCenter');
    // mapObj.plugin('AMap.Geolocation', function () {
    //     var geolocation = new AMap.Geolocation({
    //         //是否使用高精度定位，默认:true
    //         enableHighAccuracy: true,
    //         //超过10秒后停止定位，默认：无穷大
    //         timeout: 10000,
    //         maximumAge: 5000
    //     });
    //     mapObj.addControl(geolocation);
    //     geolocation.getCurrentPosition(function (status, result) {
    //     });
    //     AMap.event.addListener(geolocation, 'complete', function (data) {
    //         success(data.position.getLat(),data.position.getLng());
    //     });
    //     AMap.event.addListener(geolocation, 'error', function (data) {
    //         faulire(data);
    //     });
    // });
    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if(this.getStatus() == BMAP_STATUS_SUCCESS) {
            Convert_BD09_To_GCJ02(r.point);
            success(r.point.lat,r.point.lng)
            // var lnglat = AMap.LngLat(r.point.lng,r.point.lat)
            // AMap.convertFrom(lnglat, 'baidu',
            //     function(status,result){
            //         if (status == 'complete') {
            //             success(result.locations[0].lat,result.locations[0].lng)
            //         } else {
            //             failure(r);
            //         }
            //     });
        } else {
            failure(r);
        }
    },{
        enableHighAccuracy: true,
        maximumAge:0
    });

};

var postRequest = function (url,data,success) {
    $$.ajax({
        url: url,
        method: 'POST',
        async: false,
        dataType: 'json',
        data: data,
        success:function (data) {
            success(data)
        },
        beforeSend:function (xhr){
            myApp.showIndicator();
        },
        complete: function (xhr, status){
            myApp.hideIndicator();
        }
    });
};
var onMoviePosterError = function (i) {
    i.src = './img/wx-movie-error.png'
};
var onAlbumPosterError = function (i) {
    i.src = './img/wx-album-error.png';
};
var onCinemaPosterError = function (i) {
    i.src = './img/wx-cinema-error.png';
};
var onUserPosterError = function (i) {
    i.src = './img/wx-user-error.png';
};

myApp.showPreloader('正在定位...');
console.log('==============================>开始');
//myApp.alert($$('#baidu').attr('src'));
getCurrentLocation(function (lat, lng) {
    myApp.hidePreloader();
    latitude = lat;
    longitude = lng;
    setApplicationInit();
},function (d) {
    myApp.hidePreloader();
    latitude = 0.01;
    longitude = 0.01;
    myApp.alert('定位失败!');
    setApplicationInit();
});

var setApplicationInit = function () {
    myApp.onPageInit('cityhome', function (p) {
        $$('.page[data-page="cityhome"] .item-link ').on('click', function () {
            var id = this.dataset.id;
            var name = this.dataset.name;
            $$('.button.city-select').text(name);
            myApp.confirm('您正在切换城市，请确认', function () {
                getRegionsByCity(id, function (d) {
                    setFilterRegion(d);
                    mainView.router.back();
                });
            });
        })
    });
    myApp.onPageInit('recommendedcinemas', function (p) {
        initScrollPreloader('.page[data-page="recommendedcinemas"]');

        cinemaList = myApp.virtualList($$('.virtual-list.cinema-list'), {
            items: cinemaItems,
            template: cinemaListTemplate,
            height: 100,
        });
        if (latitude==0.01||longitude==0.01){
            myApp.alert('定位失败，请手动设置当前城市', '定位失败', function () {
                mainView.router.load({url: 'cityhome'})
            });
        } else {
            getCityByLatLng(function (data) {
                $$('.button.city-select').text(data.name);
                getRegionsByCity(data.id, function (d) {
                    setFilterRegion(d);
                });
            })
        }
        // myApp.showPreloader('正在定位...');
        // getCurrentLocation(function (lat, lng) {
        //     myApp.hidePreloader();
        //     latitude = lat;
        //     longitude = lng;
        //     // localStorage.setItem('lat', lat);// 纬度，浮点数，范围为90 ~ -90
        //     // localStorage.setItem('lng', lng);// 经度，浮点数，范围为180 ~ -180
        //
        //     getCityByLatLng(function (data) {
        //         $$('.button.city-select').text(data.name);
        //         getRegionsByCity(data.id, function (d) {
        //             setFilterRegion(d);
        //         });
        //     })
        //
        // },function (d) {
        //     myApp.hidePreloader();
        //     latitude = 0.01;
        //     longitude = 0.01;
        //     // localStorage.setItem('lat', 0.12);// 纬度，浮点数，范围为90 ~ -90
        //     // localStorage.setItem('lng', 0.13);// 经度，浮点数，范围为180 ~ -180
        //
        //     myApp.alert('定位失败，请手动设置当前城市', '定位失败', function () {
        //         mainView.router.load({url: 'cityhome'})
        //     });
        // });

        $$('.cinema-url').on('click',function (e) {
            var code = $$(this).dataset().code;
            mainView.router.load({
                // url: 'cinemahome?cinema_code='+ code +'&lat='+localStorage.getItem('lat')+'&lng='+ localStorage.getItem('lng'),
                url: 'cinemahome?cinema_code='+ code +'&lat='+ latitude +'&lng='+ longitude,
                reload: false
            });
        });

        var searchbar = myApp.searchbar('.page[data-page="recommendedcinemas"] .searchbar', {
            searchList: '.search-cinema-list',
            customSearch: true,
            onEnable: function (s) {
                $$('.search-invalid').hide();
                $$('.search-effective').show();
                searchList.deleteAllItems();
            },
            onDisable: function (s) {
                $$('.search-invalid').show();
                $$('.search-effective').hide();
            }
        });
        searchbar.input.on('keypress', function (e) {
            if (e.keyCode == 13) {
                if (!searchbar.input.val().trim()) {
                    return;
                }
                var parameter = {
                    searchKey: searchbar.input.val().trim(),
                    // lat: localStorage.getItem('lat'),
                    lat: latitude,
                    // lng: localStorage.getItem('lng')
                    lng: longitude
                };
                postRequest('getsearchedcinemas',parameter,function (data) {
                    if (data.errorMessage) {
                        myApp.alert(data.errorMessage);
                    } else {
                        searchList.replaceAllItems(data.cinemas);
                    }
                });
            }
        });

        var searchs = [];
        var searchList = myApp.virtualList($$('.virtual-list.search-cinema-list'), {
            items: searchs,
            template: cinemaListTemplate,
            height: 100
        });

        $$('.page[data-page="recommendedcinemas"] .infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            getRecommendedCinemas();
        });

        if ($$('.cinema-banner-swiper').find('a').length > 1 ){
            myApp.swiper('.cinema-banner-swiper', {
                pagination:'.cinema-banner-swiper .swiper-pagination',
                spaceBetween: 50,
                autoplay: 2500,
                autoplayDisableOnInteraction: false,
                loop: true,
                // freeMode:true
            });
        } else {
            myApp.swiper('.cinema-banner-swiper', {
                pagination:'.cinema-banner-swiper .swiper-pagination',
                spaceBetween: 50,
                // freeMode:true
            });
        }

    });
    myApp.onPageInit('cinemahome', function (page) {

        if ($$('.swiper-container.swiper-posters').length > 0) {
            myApp.swiper('.swiper-container.swiper-posters', {
                spaceBetween: 5,
                slidesPerView: 3.5,
                speed: 600,
                lazyLoading: true,
                preloadImages: false,
                freeMode:true
            });
        }
        if ($$('.swiper-container.swiper-movies').length > 0) {
            myApp.swiper('.swiper-container.swiper-movies', {
                spaceBetween: 5,
                slidesPerView: 3.5,
                speed: 600,
                lazyLoading: true,
                preloadImages: false,
                freeMode:true
            });
        }

        $$('.navigation').on('click', function (e) {
            var dataset = $$(this).dataset();
            wx.openLocation({
                latitude: parseFloat(dataset.lat),
                longitude: parseFloat(dataset.lng),
                name: dataset.name,
                address: '地址：' + dataset.site + '[右侧点击为您找到线路→_→]',
                scale: 14
            })
        });

        $$('.cinema-collection').on('click', function (e) {
            var that = $$(this);
            if (loading) return;
            loading = true;
            var parameter = {
                type: 1,
                code: page.query.cinema_code
            };
            postRequest('setcollection',parameter,function (data) {
                if (data.errorMessage) {
                    if (data.errorMessage == '请注册会员！'){
                        myApp.alert(data.errorMessage,function () {
                            mainView.router.load({
                                url: 'regist'
                            })
                        });
                    } else {
                        myApp.alert(data.errorMessage);
                    }
                } else {
                    if (data.insertId) {
                        that.find('img').attr('src', './img/set_movie_collection_w_2.png');
                        that.find('span').text('已收藏');
                        that.addClass('color-gray');
                        that.removeClass('color-custom');
                    } else {
                        that.find('img').attr('src', './img/set_movie_collection_w_1.png');
                        that.find('span').text('收藏');
                        that.addClass('color-custom');
                        that.removeClass('color-gray');
                    }
                }
                loading = false;
            });
        });
    });
    myApp.onPageInit('recommendedmovies', function (p) {
        initScrollPreloader('.page[data-page="recommendedmovies"]');

        $$('.list-deployable .list-more a').on('click',function (e) {
            if ($$(this).parents('.list-deployable').find('.list-hidden').length>0){
                $$(this).parents('.list-deployable').find('.list-hidden').addClass('list-spread');
                $$(this).parents('.list-deployable').find('.list-hidden').removeClass('list-hidden');
                $$(this).text('收起');
            } else {
                $$(this).parents('.list-deployable').find('.list-spread').addClass('list-hidden');
                $$(this).parents('.list-deployable').find('.list-spread').removeClass('list-spread');
                $$(this).text('更多');
            }
        });

        $$('.popup-filter').on('popup:opened', function () {
            if ($$('.popup-overlay').length>0){
                $$('.popup-overlay').remove()
            }
        });

        var searchbar = myApp.searchbar('.page[data-page="recommendedmovies"] .searchbar', {
            searchList: '.search-list',
            customSearch: true,
            onEnable: function (s) {
                $$('.search-invalid').hide();
                $$('.search-effective').show();
                searchList.deleteAllItems();
            },
            onDisable: function (s) {
                $$('.search-invalid').show();
                $$('.search-effective').hide();
            }
        });
        searchbar.input.on('keypress', function (e) {
            if (e.keyCode == 13) {
                if (!searchbar.input.val().trim()) {
                    return;
                }
                var parameter = {
                    searchKey: searchbar.input.val().trim()
                };
                postRequest('getsearchedmovies',parameter,function (data) {
                    if (data.errorMessage) {
                        myApp.alert(data.errorMessage);
                    } else {
                        searchList.replaceAllItems(data.movies);
                    }
                });
            }
        });
        var searchs = [];
        var searchList = myApp.virtualList($$('.page[data-page="recommendedmovies"] .virtual-list.search-list'), {
            items: searchs,
            template: movieListTemplate,
            height: 124,
        });
        var items = [];
        var list = myApp.virtualList($$('.page[data-page="recommendedmovies"] .virtual-list.movie-album-list'), {
            items: items,
            template: albumListTemplate,
            onItemsAfterInsert: function (list, fragment) {
                // if (list.items.length >0 ){
                //     for (var i=0; i<list.items.length;i++){
                //         var c = $$('#canvas-'+list.items[i].album_id);
                //         c.each(function () {
                //             var cxt = this.getContext('2d') ;
                //             var width = $$(this).width();
                //             var img = new Image();
                //             img.src = CND_URL + '/ALBUM/'+ list.items[i].album_id + '/'+ list.items[i].wx_poster;
                //             img.onload = function () {
                //                 cxt.drawImage(img,0,0);
                //                 var imgData = cxt.getImageData(0,135,width,100);
                //                 for (var y=0;y<100;y++){
                //                     for (var i=0;i<width*4;i+=4) {
                //                         var offset = y*width*4
                //                         if (i>(50+y)*4 && i< (80-y)*4){
                //                         }else {
                //                             imgData.data[i+offset+0]=0;
                //                             imgData.data[i+offset+1]=0;
                //                             imgData.data[i+offset+2]=0;
                //                             imgData.data[i+offset+3]=0;
                //                         }
                //                     }
                //                 }
                //                 cxt.putImageData(imgData,0,135);
                //             };
                //
                //         });
                //     }
                // }
                myApp.swiper('.swiper-movie', {
                    speed: 600,
                    spaceBetween: 0,
                    slidesPerView: 3,
                    freeMode:true
                    // centeredSlides: true,
                    // slidesPerColumn:3,
                    // slidesOffsetBefore:5,
                    // slidesOffsetAfter:5
                });
            },
            height: 404
        });

        var request = {page: 0};
        getRecommendedMovies(request, function (data) {
            if (data.errorMessage) {
                removeScrollPreloader('.page[data-page="recommendedmovies"]');
            } else {
                if (data.isLast) {
                    removeScrollPreloader('.page[data-page="recommendedmovies"]');
                }
                list.appendItems(data.albums);
                if (list.items.length >0 ){
                    for (var i=0; i<list.items.length;i++){
                        var c = $$('.album-album-collection.album_'+list.items[i].album_id);
                        c.each(function () {
                            var that = $$(this);
                            that.on('click',function (e) {
                                if (loading) return;
                                loading = true;
                                var parameter = {
                                    type: 2,
                                    code: list.items[i].album_id
                                };
                                postRequest('setcollection',parameter,function (data) {
                                    if (data.errorMessage) {
                                        if (data.errorMessage == '请注册会员！'){
                                            myApp.alert(data.errorMessage,function () {
                                                mainView.router.load({
                                                    url: 'regist'
                                                })
                                            });
                                        } else {
                                            myApp.alert(data.errorMessage);
                                        }
                                    } else {
                                        if (data.insertId) {
                                            that.text('已收藏');
                                            that.removeClass('color-custom');
                                            that.addClass('color-gray');
                                        } else {
                                            that.text('收藏');
                                            that.removeClass('color-gray');
                                            that.addClass('color-custom');
                                        }
                                    }
                                    loading = false;
                                });
                            })
                        });
                        if (list.items[i].movies.length >0){
                            for (var j=0; j<list.items[i].movies.length;j++){
                                var m = $$('.album-movie-collection.movie_'+list.items[i].album_id+'_'+list.items[i].movies[j].mid);
                                m.each(function () {
                                    var that = $$(this);
                                    that.on('click',function (e) {
                                        if (loading) return;
                                        loading = true;

                                        var that = $$(this);
                                        var parameter = {
                                            type: 0,
                                            code: list.items[i].movies[j].mid
                                        };
                                        postRequest('setcollection',parameter,function (data) {
                                            if (data.errorMessage) {
                                                if (data.errorMessage == '请注册会员！'){
                                                    myApp.alert(data.errorMessage,function () {
                                                        mainView.router.load({
                                                            url: 'regist'
                                                        })
                                                    });
                                                } else {
                                                    myApp.alert(data.errorMessage);
                                                }
                                            } else {
                                                if (data.insertId) {
                                                    that.find('img').attr('src', './img/wx-set_movie_collection_2.png');
                                                } else {
                                                    that.find('img').attr('src', './img/wx-set_movie_collection_1.png');
                                                }
                                            }
                                            loading = false;
                                        });
                                    })
                                })
                            }
                        }

                    }
                }
                request.page++;
            }
        });

        $$('.page[data-page="recommendedmovies"] .infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            getRecommendedMovies(request, function (data) {
                if (data.errorMessage) {
                    removeScrollPreloader('.page[data-page="recommendedmovies"]');
                } else {
                    if (data.isLast) {
                        removeScrollPreloader('.page[data-page="recommendedmovies"]');
                    }
                    list.appendItems(data.albums);
                    if (list.items.length >0 ){
                        for (var i=0; i<list.items.length;i++){
                            var c = $$('.album-album-collection.album_'+list.items[i].album_id);
                            c.each(function () {
                                var that = $$(this);
                                that.on('click',function (e) {
                                    if (loading) return;
                                    loading = true;
                                    var parameter = {
                                        type: 2,
                                        code: list.items[i].album_id
                                    };
                                    postRequest('setcollection',parameter,function (data) {
                                        if (data.errorMessage) {
                                            if (data.errorMessage == '请注册会员！'){
                                                myApp.alert(data.errorMessage,function () {
                                                    mainView.router.load({
                                                        url: 'regist'
                                                    })
                                                });
                                            } else {
                                                myApp.alert(data.errorMessage);
                                            }
                                        } else {
                                            if (data.insertId) {
                                                that.text('已收藏');
                                                that.removeClass('color-custom');
                                                that.addClass('color-gray');
                                            } else {
                                                that.text('收藏');
                                                that.removeClass('color-gray');
                                                that.addClass('color-custom');
                                            }
                                        }
                                        loading = false;
                                    });
                                })
                            });
                            if (list.items[i].movies.length >0){
                                for (var j=0; j<list.items[i].movies.length;j++){
                                    var m = $$('.album-movie-collection.movie_'+list.items[i].album_id+'_'+list.items[i].movies[j].mid);
                                    m.each(function () {
                                        var that = $$(this);
                                        that.on('click',function (e) {
                                            if (loading) return;
                                            loading = true;

                                            var that = $$(this);
                                            var parameter = {
                                                type: 0,
                                                code: list.items[i].movies[j].mid
                                            };
                                            postRequest('setcollection',parameter,function (data) {
                                                if (data.errorMessage) {
                                                    if (data.errorMessage == '请注册会员！'){
                                                        myApp.alert(data.errorMessage,function () {
                                                            mainView.router.load({
                                                                url: 'regist'
                                                            })
                                                        });
                                                    } else {
                                                        myApp.alert(data.errorMessage);
                                                    }
                                                } else {
                                                    if (data.insertId) {
                                                        that.find('img').attr('src', './img/wx-set_movie_collection_2.png');
                                                    } else {
                                                        that.find('img').attr('src', './img/wx-set_movie_collection_1.png');
                                                    }
                                                }
                                                loading = false;
                                            });
                                        })
                                    })
                                }
                            }

                        }
                    }
                    request.page++;
                }
            });
        });

        if ($$('.movie-banner-swiper').find('a').length > 1 ){
            myApp.swiper('.movie-banner-swiper', {
                pagination:'.movie-banner-swiper .swiper-pagination',
                spaceBetween: 50,
                autoplay: 2500,
                autoplayDisableOnInteraction: false,
                loop: true,
                // freeMode:true
            });
        } else {
            myApp.swiper('.movie-banner-swiper', {
                pagination:'.movie-banner-swiper .swiper-pagination',
                spaceBetween: 50,
                // freeMode:true
            });
        }

    });
    myApp.onPageInit('filtedmovies', function (p) {
        initScrollPreloader('.page[data-page="filtedmovies"]');
        var items = [];
        var list = myApp.virtualList($$('.virtual-list.movie-filter-list'), {
            items: items,
            template: movieListTemplate,
            height: 124
        });
        var request = {
            mode: p.query.mode,
            parameter: p.query.parameter,
            page: 0
        };
        getFilterMovies(request, function (data) {
            if (data.errorMessage) {
                removeScrollPreloader('.page[data-page="filtedmovies"]');
            } else {
                if (data.isLast) {
                    removeScrollPreloader('.page[data-page="filtedmovies"]');
                }
                list.appendItems(data.movies);
                request.page++;
            }
        });

        $$('.page[data-page="filtedmovies"] .infinite-scroll').on('infinite', function (e) {
            if (loading) return;
            loading = true;
            getFilterMovies(request, function (data) {
                if (data.errorMessage) {
                    removeScrollPreloader('.page[data-page="filtedmovies"]');
                } else {
                    if (data.isLast) {
                        removeScrollPreloader('.page[data-page="filtedmovies"]');
                    }
                    list.appendItems(data.movies);
                    request.page++;
                }
                loading = false;
            });
        });

    });
    myApp.onPageInit('moviehome', function (p) {
        $$('.open-slider-modal').on('click', function () {
            var parameter = {
                mid: p.query.mid,
                lat: latitude,
                lng: longitude
            };
            postRequest('getcinemasbymid',parameter,function (data) {
                if (data.errorMessage) {
                    myApp.alert(data.errorMessage);
                } else {
                    var tmp = '';
                    for (var i = 0; i < data.rows.length; i++) {
                        var distance = Math.sqrt(data.rows[i].distance)*100*1000;
                        if (distance < 1000) {
                            distance = Math.round(distance)+"m";
                        } else if (distance > 1000 && distance < 100000) {
                            var jl = distance / 1000.0;
                            distance = jl.toFixed(1) + "km";
                        } else {
                            distance = ">100km";
                        }
                        tmp +=
                            '<div class="swiper-slide">' +
                            '<a onclick="myApp.closeModal()" href="cinemahome?cinema_code=' + data.rows[i].cinema_code + '&from=movie&lat='+ latitude + '&lng='+ longitude + '&random='+ Math.random() +'">' +
                            '<img src="' + data.rows[i].cinema_picture + '" width="150" height="150" onerror="onCinemaPosterError(this)">' +
                            '<p class="color-black">' + data.rows[i].cinema_name + '('+ distance +')'+'</p>' +
                            '</a>' +
                            '</div>';

                    }
                    var modal = myApp.modal({
                        title: "可点播影院",
                        afterText: '<div class="swiper-container" style="width: auto; margin:5px -15px -15px">' +
                        '<div class="swiper-wrapper">' + tmp +
                        '</div>' +
                        '</div>',
                        buttons: [{text: '关闭', close: true}]
                    });
                    myApp.swiper(
                        $$(modal).find('.swiper-container'), {
                            freeMode:true
                        });
                }
            })
        });

        $$('.movie-collection').on('click', function (e) {
            var that = $$(this);
            if (loading) return;

            loading = true;
            var parameter = {
                type: 0,
                code: p.query.mid
            };
            postRequest('setcollection',parameter,function (data) {
                if (data.errorMessage) {
                    if (data.errorMessage == '请注册会员！'){
                        myApp.alert(data.errorMessage,function () {
                            mainView.router.load({
                                url: 'regist'
                            })
                        });
                    } else {
                        myApp.alert(data.errorMessage);
                    }
                } else {
                    if (data.insertId) {
                        that.find('img').attr('src', './img/set_movie_collection_w_2.png');
                        that.find('span').text('已收藏');
                        that.addClass('color-gray');
                        that.removeClass('color-custom');
                    } else {
                        that.find('img').attr('src', './img/set_movie_collection_w_1.png');
                        that.find('span').text('收藏');
                        that.addClass('color-custom');
                        that.removeClass('color-gray');
                    }
                }
                loading = false;
            });
        })
    });
    myApp.onPageInit('cinemaroomtype', function (page) {
        var dataset = $$('.page[data-page="cinemaroomtype"]').dataset();
        $$('.booking-submit').on('click', function (e) {
            var formData = myApp.formToJSON('#booking-form');
            if (!formData.bookingDate) {
                myApp.alert('请选择观影日期!')
            } else if (!formData.startTime) {
                myApp.alert('请选择到店时间!')
            }
            // else if (!formData.watchingMinutes) {
            //     myApp.alert('请选择观影时长')
            // }
            // else if (!formData.numbers) {
            //     myApp.alert('请选择观影人数')
            // }
            else if (!formData.bookingContact) {
                myApp.alert('请填写联系人')
            } else if (!formData.bookingCode) {
                myApp.alert('请填写联系电话')
            } else {
                var zero = formData.bookingDate + ' ' + '00:00:00';
                var zeroTime = Date.parse(zero);
                var select = zeroTime + parseInt(pickerStartTime.cols[0].value) * 60 * 60 * 1000 + parseInt(pickerStartTime.cols[2].value) * 60 * 1000;
                var now = new Date().getTime();
                var phone = /^1[34578]\d{9}$/;
                //formData.userComment = formData.userComment.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");

                if ((select - now) < 3 * 60 * 60 * 1000) {
                    myApp.alert('只能预约三小时以后的场次！', '请重新选择到店时间！');
                } else if ($$('#bookingContact').val().length > 30) {
                    myApp.alert('联系人输入过长！', '请重新填写联系人！');
                } else if (!phone.test(formData.bookingCode)) {
                    myApp.alert('联系电话输入格式错误！', '请重新填写联系电话！');
                } else if ($$('#userComment').val().length > 30) {
                    myApp.alert('留言输入过长！', '请重新填写留言！');
                } else {
                    var message = '观影日期:' + formData.bookingDate + '\<br\>';
                    message += '到店时间:' + formData.startTime + '\<br\>';
                    // message += '观影时长: ' + formData.watchingMinutes + '\<br\>';
                    message += '联系人: ' + formData.bookingContact + '\<br\>';
                    message += '联系电话: ' + formData.bookingCode + '\<br\>';
                    myApp.confirm(message, '请确认您的预约信息', function () {
                        formData.cinemaCode = dataset.cinemaCode;
                        formData.roomtypeId = dataset.roomtypeId;
                        formData.startTime = pickerStartTime.cols[0].value + ':' + pickerStartTime.cols[2].value;
                        formData.watchingMinutes = pickerStartTime.cols[4].value;
                        //formData.watchingMinutes = pickerWatching.cols[0].value;
                        //formData.numbers = parseInt(dataset.peopleLimit);
                        //formData.numbers = pickerNumbers.cols[0].value;
                        postRequest('submitbooking',formData,function (data) {
                            if (data.errorMessage) {
                                myApp.alert(data.errorMessage, '预约失败！');
                            } else {
                                var success = '您的预约信息已提交！您可在个人信息中找到您的预约信息！\<br\>' +
                                    '订单号： ' + data.booking_id;
                                myApp.alert(success, '预约成功！', function () {
                                    mainView.back()
                                });
                            }
                        });
                    });
                }

            }
        });

        var now = new Date();
        var year = now.getFullYear();
        var month = now.getMonth() + 1;
        var date = now.getDate();
        var hours = now.getHours();
        if (month < 10) {
            month = '0' + month;
        }
        if (date < 10) {
            date = '0' + date;
        }
        //可预约开始时间
        var arg1 = parseInt(dataset.bookingStart.split(':')[0]);
        //可预约结束时间
        var arg2 = parseInt(dataset.bookingEnd.split(':')[0]);
        //结束超过超过凌晨处理
        if (arg2 < 12) {
            arg2 = arg2 + 24;
        }
        //最少时长范围
        var startTimezone = parseInt(dataset.startTimezone);
        //可增加时长范围
        var addTimezone = parseInt(dataset.addTimezone);

        var pickerStartTime = myApp.picker({
            input: '#startTime',
            toolbarCloseText: '关闭',
            formatValue: function (p, values, displayValues) {
                return displayValues[0] + ':' + displayValues[1] + '('+ displayValues[2] +')';
            },
            rotateEffect: true,
            cols: [
                {
                    values: (function () {
                        var min = arg1;
                        var max = arg2;
                        if (arg1 < hours) {
                            min = hours + 1;
                        }

                        var arr = [];
                        for (var i = min; i <= max; i++) {
                            if (i < 10) {
                                arr.push('0' + i);
                            } else {
                                arr.push(i);
                            }
                        }
                        return arr;
                    })(),
                    displayValues: (function () {
                        var min = arg1;
                        var max = arg2;
                        if (arg1 < hours) {
                            min = hours + 1;
                        }
                        var arr = [];
                        for (var i = min; i <= max; i++) {
                            var hour = i;
                            if (hour >= 24) {
                                hour = i - 24;
                            }
                            if (hour < 10) {
                                arr.push('0' + hour);
                            } else {
                                arr.push(hour);
                            }
                        }
                        return arr;
                    })()
                },
                {
                    divider: true,
                    content: ':'
                },
                {
                    values: ['00', '15', '30', '45']
                },
                {
                    divider: true,
                    content: ''
                },
                {
                    values: (function () {
                        var arr = [];
                        for (var i = startTimezone; i <= 600; i = i + addTimezone) {
                            arr.push(i);
                        }
                        return arr;
                    })(),
                    displayValues: (function () {
                        var arr = [];
                        for (var i = startTimezone; i <= 600; i = i + addTimezone) {

                            var h = parseInt(i / 60);
                            var m = i % 60;
                            if (m < 10) {
                                m = '0' + m;
                            }
                            arr.push(h + '时' + m + '分');
                        }
                        return arr;
                    })()
                }
            ]
        });

        // var startTimezone = parseInt(dataset.startTimezone);
        // var addTimezone = parseInt(dataset.addTimezone);
        // var pickerWatching = myApp.picker({
        //     input: '#watchingMinutes',
        //     toolbarCloseText: '关闭',
        //     formatValue: function (p, values, displayValues) {
        //         return displayValues[0];
        //     },
        //     rotateEffect: true,
        //     cols: [
        //         {
        //             values: (function () {
        //                 var arr = [];
        //                 for (var i = startTimezone; i <= 600; i = i + addTimezone) {
        //                     arr.push(i);
        //                 }
        //                 return arr;
        //             })(),
        //             displayValues: (function () {
        //                 var arr = [];
        //                 for (var i = startTimezone; i <= 600; i = i + addTimezone) {
        //
        //                     var h = parseInt(i / 60);
        //                     var m = i % 60;
        //                     if (m < 10) {
        //                         m = '0' + m;
        //                     }
        //                     arr.push(h + '小时' + m + '分钟');
        //                 }
        //                 return arr;
        //             })()
        //         }
        //     ]
        // });

        // var peopleLimit = parseInt(dataset.peopleLimit);
        // var pickerNumbers = myApp.picker({
        //     input: '#numbers',
        //     toolbarCloseText: '关闭',
        //     formatValue: function (p, values, displayValues) {
        //         return displayValues[0];
        //     },
        //     rotateEffect: true,
        //     cols: [
        //         {
        //             values: (function () {
        //                 var arr = [];
        //                 for (var i = 1; i <= peopleLimit; i++) {
        //                     arr.push(i);
        //                 }
        //                 return arr;
        //             })(),
        //             displayValues: (function () {
        //                 var arr = [];
        //                 for (var i = 1; i <= peopleLimit; i++) {
        //                     arr.push(i + '人');
        //                 }
        //                 return arr;
        //             })()
        //
        //         }
        //     ]
        // });


        $$('input[type="radio"]').on('change', function () {
            if (pickerStartTime.cols[0].displayValues) {
                pickerStartTime.cols[0].displayValues = [];
            }
            if (pickerStartTime.cols[0].values) {
                pickerStartTime.cols[0].values = [];
            }

            if (myApp.formToJSON('#booking-form').bookingDate == (year + '-' + month + '-' + date)) {
                var min = arg1;
                var max = arg2;
                if (arg1 < hours) {
                    min = hours + 1;
                }
                for (var i = min; i <= max; i++) {
                    if (i < 10) {
                        pickerStartTime.cols[0].values.push('0' + i);
                    } else {
                        pickerStartTime.cols[0].values.push(i);
                    }
                    var h = i;
                    if (h >= 24) {
                        h = i - 24;
                    }
                    if (h >= 24) {
                        h = i - 24;
                    }
                    if (h < 10) {
                        pickerStartTime.cols[0].displayValues.push('0' + h);
                    } else {
                        pickerStartTime.cols[0].displayValues.push(h);
                    }
                }
            } else {
                var min = arg1;
                var max = arg2;
                for (var i = min; i <= max; i++) {
                    if (i < 10) {
                        pickerStartTime.cols[0].values.push('0' + i);
                    } else {
                        pickerStartTime.cols[0].values.push(i);
                    }

                    var hour = i;
                    if (hour >= 24) {
                        hour = i - 24;
                    }
                    if (hour >= 24) {
                        hour = i - 24;
                    }
                    if (hour < 10) {
                        pickerStartTime.cols[0].displayValues.push('0' + hour);
                    } else {
                        pickerStartTime.cols[0].displayValues.push(hour);
                    }
                }
            }
        });

    });
    myApp.onPageInit('bookingorders', function (page) {
        var items1 = [];
        var items2 = [];
        var items3 = [];
        var list1 = myApp.virtualList($$('#tab1 .virtual-list'), {
            items: items1,
            template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
            '<div class="card-header no-border">' +
            '   <div class="facebook-name">{{this.cinema_name}}</div>' +
            '   <div class="facebook-date">{{this.createtime}}</div>' +
            '</div>' +
            '<div class="card-content">' +
            '   <div class="card-content-inner">' +
            '       <p>影厅：{{this.roomtype_name}}</p>' +
            '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
            '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
            '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
            '   </div>' +
            '</div>' +
            '<div class="card-footer">' +
            '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
            '   <span></span>' +
            '   <a href="#" class="color-custom link cancel-booking-{{this.booking_id}}" data-booking-id="{{this.booking_id}}">取消</a>' +
            '</div>' +
            '</li>',
            height: 259
        });

        var list2 = myApp.virtualList($$('#tab2 .virtual-list'), {
            items: items2,
            template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
            '<div class="card-header no-border">' +
            '   <div class="facebook-name">{{this.cinema_name}}</div>' +
            '   <div class="facebook-date">{{this.createtime}}</div>' +
            '</div>' +
            '<div class="card-content">' +
            '   <div class="card-content-inner">' +
            '       <p>影厅：{{this.roomtype_name}}</p>' +
            '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
            '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
            '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
            '   </div>' +
            '</div>' +
            '<div class="card-footer">' +
            '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
            '   <span></span>' +
            '   <span></span>' +
            '</div>' +
            '</li>',
            height: 259
        });

        var list3 = myApp.virtualList($$('#tab3 .virtual-list'), {
            items: items3,
            template: '<li class="card facebook-card" data-booking-id="{{this.booking_id}}">' +
            '<div class="card-header no-border">' +
            '   <div class="facebook-name">{{this.cinema_name}}</div>' +
            '   <div class="facebook-date">{{this.createtime}}</div>' +
            '</div>' +
            '<div class="card-content">' +
            '   <div class="card-content-inner">' +
            '       <p>影厅：{{this.roomtype_name}}</p>' +
            '       <p>日期：{{this.booking_date}} ({{formatChineseWeek this.week_day}})</p>' +
            '       <p>时间：{{this.start_time}} - {{this.end_time}}</p>' +
            '       <p class="color-gray">备注：{{this.user_comment}}</p>' +
            '   </div>' +
            '</div>' +
            '<div class="card-footer">' +
            '   <span>订单号:{{this.order_code}}</span><span></span><span></span><span></span><span></span>' +
            '   <span>已取消</span>' +
            '   <span></span>' +
            '</div>' +
            '</li>',
            height: 259
        });

        var req = {
            state: 1,
            page1: 0,
            page2: 0,
            page3: 0,
        };
        $$('#tab1').on('show', function () {
            req.state = 1;
            if (req.page1 == 0) {
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                        $$( '#tab1  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab1  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                            $$( '#tab1  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab1  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        for (var i = 0; i < data.orders.length; i++) {
                            list1.appendItem(data.orders[i]);
                            bindCancelBooking(list1, data.orders[i].booking_id);
                        }
                        req.page1++;
                    }
                });
            }
            $$('#tab1.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                        $$( '#tab1  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab1  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab1.infinite-scroll'));
                            $$( '#tab1  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab1  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        for (var i = 0; i < data.orders.length; i++) {
                            list1.appendItem(data.orders[i]);
                            bindCancelBooking(list1, data.orders[i].booking_id);
                        }
                        req.page1++;
                    }
                    loading = false;
                });
            })


        });
        $$('#tab2').on('show', function () {
            req.state = 2;
            if (req.page2 == 0) {
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                        $$( '#tab2  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab2  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                            $$( '#tab2  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab2  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        list2.appendItems(data.orders);
                        req.page2++;
                    }
                });
            }
            $$('#tab2.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                        $$( '#tab2  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab2  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab2.infinite-scroll'));
                            $$( '#tab2  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab2  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        list2.appendItems(data.orders);
                        req.page2++;
                    }
                    loading = false;
                });
            })
        });
        $$('#tab3').on('show', function () {
            req.state = 3;
            if (req.page3 == 0) {
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                        $$( '#tab3  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab3  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                            $$( '#tab3  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab3  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        list3.appendItems(data.orders);
                        req.page3++;
                    }
                });
            }
            $$('#tab3.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getBookingOrderList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                        $$( '#tab3  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab3  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab3.infinite-scroll'));
                            $$( '#tab3  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab3  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        list3.appendItems(data.orders);
                        req.page3++;
                    }
                    loading = false;
                });
            })
        });
        myApp.showTab('#tab1');
        function bindCancelBooking(list, id) {
            $$('.cancel-booking-' + id).on('click', function (event) {

                var e = '是否取消该订单？';
                var a = '请确认！';
                var req = $$(this).dataset();
                var index = -1;
                for (var i = 0; i < list.items.length; i++) {
                    if (req.bookingId == list.items[i].booking_id) {
                        index = i;
                        break;
                    }
                }

                myApp.confirm(e, a, function () {
                    $$.post('cancelbooking', req, function (data) {
                        data = JSON.parse(data);
                        if (data.errorMessage) {
                            myApp.alert(data.errorMessage, '取消失败！');
                            return;
                        }
                        myApp.alert('您已成功取消订单！', '取消成功！', function () {
                            list.deleteItem(index);
                        });
                    })
                }, function () {
                });
            });
        }
    });
    myApp.onPageInit('cardbinding', function (page) {
        $$('.btn-bind').on('click', function (e) {
            var formData = myApp.formToData('#card-bind-form');
            postRequest('setcardbinding',formData,function (data) {
                myApp.alert(data);
            });
        });
    });
    myApp.onPageInit('usercenter', function (page) {

        var myPhotoBrowser = myApp.photoBrowser({
            photos: [
                $$('.wx-headimg').attr('src')
            ],
            zoom: 400,
            navbar: false,
            toolbar: false
        });
        $$('.wx-headimg').on('click', function (e) {
            myPhotoBrowser.open();
        })

    });
    myApp.onPageInit('cardpackage', function (page) {

        var tel = $$('.wx-bestvcard').text();
        var canvas = qrcanvas({
            data: tel,
            cellSize: 10
        });
        var navbarTemplate =
            +'<div class="navbar-inner">'
            + '<div class="left sliding">'
            + '<a href="#" class="link close-popup photo-browser-close-link {{#unless backLinkText}}icon-only{{/unless}} {{js "this.type === \'page\' ? \'back\' : \'\'"}}">'
            + '<i class="icon icon-back {{iconsColorClass}}"></i>'
            + '{{#if backLinkText}}<span>{{backLinkText}}</span>{{/if}}'
            + '</a>'
            + '</div>'
            + '<div class="right"></div>'
            + '</div>'
            + '</div>';
        var photoTemplate = '<div class="page-content login-screen-content" style="width: 100%;background-color: #0a6ebd"><div class="login-screen-title">尊享会员特权</div>'
            + '<div style="text-align: center;">'
            + '<div class="container card"  style="margin:auto;padding:20px 10px;width: 85%;background-color: white"></div></div>'
            + '</div>';
        var myPhotoBrowser = myApp.photoBrowser({
            photos: [' '],
            backLinkText: '关闭二维码',
            toolbar: false,
            navbarTemplate: navbarTemplate,
            photoTemplate: photoTemplate,
            type: 'page',
        });


        $$('.wx-qrcode').on('click', function () {
            myPhotoBrowser.open();
            myPhotoBrowser.container.find('.container').append(canvas);
            myPhotoBrowser.container.find('.container').append('<div><h4>' + tel + '</h4></div>');
        });
    });
    myApp.onPageInit('activation', function (page) {
        var showSuccessModel = function () {
            myApp.modal({
                afterText:'<div style="width: auto; margin: 15px;text-align: center">' +
                '<a class="external" onclick="myApp.closeModal()" href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb8559b450f58c079&redirect_uri=http%3A%2F%2Fweixin.bestmovie.com.cn%2Fusercenter&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect" style="position: absolute;top: 12px;right: 12px">' +
                // '<a class="external" onclick="myApp.closeModal()" href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxaf378ab4ba9fb3da&redirect_uri=http%3A%2F%2Fweixin.tooking.cn%2Fusercenter&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect" style="position: absolute;top: 12px;right: 12px">' +
                '<img src="./img/wx-activation-close.png" width="12" height="12">' +
                '</a>' +
                '<img src="./img/wx-activation-success.png" width="212" height="242" style="display:block">'+
                '</div>',
            });
        };

        if ($$('.page[data-page="activation"]').dataset().success){
            showSuccessModel();
        }
        $$('#graphiccode').attr("src", 'graphiccode?random'+ Math.random());
        $$('#graphiccode').on('click', function () {
            if (loading){
                return;
            }
            loading = true;
            $$(this).attr("src", 'graphiccode?random'+ Math.random());
            setTimeout(function () {
                loading = false;
            }, 1000);
        });

        $$('#identifyingcode').on('click', function (e) {
            var formData = myApp.formToData('#activation-form');
            if (!phoneNumberCheck(formData.phonenumber)) {
                myApp.alert('请输入有效的手机号码！');
                return;
            }
            if (!graphicCodeCheck(formData.graphiccode)) {
                myApp.alert('请输入正确的图形验证码！');
                return;
            }
            var parameter = {
                graphiccode: formData.graphiccode.trim(),
                phonenumber: formData.phonenumber.trim(),
            };
            postRequest('wxidentifyingcode',parameter,function (data) {
                if (data.errorMessage) {
                    myApp.alert(data.errorMessage);
                } else if (data.error_response) {
                    myApp.alert('短信发送失败！');
                } else if (data.alibaba_aliqin_fc_sms_num_send_response.result.err_code == 0) {
                    myApp.alert('短信发送成功，请注意查收！');
                    countdown = 60;
                    settime($$('#identifyingcode'));
                } else {
                    myApp.alert(data.alibaba_aliqin_fc_sms_num_send_response.result.msg);
                }
            });
        });

        $$('#activation').on('click', function () {
            var formData = myApp.formToData('#activation-form');
            if (!phoneNumberCheck(formData.phonenumber)) {
                myApp.alert('请输入有效的手机号码！');
                return;
            }
            if (!graphicCodeCheck(formData.graphiccode)) {
                myApp.alert('请输入正确的图形验证码！');
                return;
            }
            if (!identifyingCodeCheck(formData.identifyingcode)) {
                myApp.alert('请输入正确的短信验证码！');
                return;
            }
            $$.ajax({
                url: 'activation',
                method: 'POST',
                dataType: 'json',
                async: false,
                data: {
                    identifyingcode: formData.identifyingcode.trim(),
                    phonenumber: formData.phonenumber.trim(),
                },
                success: function (data, status, xhr) {
                    if (data.errorMessage) {
                        myApp.alert(data.errorMessage);
                    } else {
                        showSuccessModel();
                    }
                }
            });
        });
    });
    myApp.onPageInit('register', function (page) {

        $$('#graphiccode').attr("src", 'graphiccode?random'+ Math.random());
        $$('#graphiccode').on('click', function () {
            if (loading){
                return;
            }
            loading = true;
            $$(this).attr("src", 'graphiccode?random'+ Math.random());
            setTimeout(function () {
                loading = false;
            }, 1000);
        });

        $$('#identifyingcode').on('click', function (e) {
            var formData = myApp.formToData('#register-form');
            if (!phoneNumberCheck(formData.phonenumber)) {
                myApp.alert('请输入有效的手机号码！');
                return;
            }
            if (!graphicCodeCheck(formData.graphiccode)) {
                myApp.alert('请输入正确的图形验证码！');
                return;
            }
            var parameter = {
                graphiccode: formData.graphiccode.trim(),
                phonenumber: formData.phonenumber.trim(),
            };
            postRequest('wxidentifyingcode',parameter,function (data) {
                if (data.errorMessage) {
                    myApp.alert(data.errorMessage);
                } else if (data.error_response) {
                    myApp.alert('短信发送失败！');
                } else if (data.alibaba_aliqin_fc_sms_num_send_response.result.err_code == 0) {
                    myApp.alert('短信发送成功，请注意查收！');
                    countdown = 60;
                    settime($$('#identifyingcode'));
                } else {
                    myApp.alert(data.alibaba_aliqin_fc_sms_num_send_response.result.msg);
                }
            });
        });

        $$('#register').on('click', function () {
            var formData = myApp.formToData('#register-form');
            if (!phoneNumberCheck(formData.phonenumber)) {
                myApp.alert('请输入有效的手机号码！');
                return;
            }
            if (!graphicCodeCheck(formData.graphiccode)) {
                myApp.alert('请输入正确的图形验证码！');
                return;
            }
            if (!identifyingCodeCheck(formData.identifyingcode)) {
                myApp.alert('请输入正确的短信验证码！');
                return;
            }
            $$.ajax({
                url: 'activation',
                method: 'POST',
                dataType: 'json',
                async: false,
                data: {
                    identifyingcode: formData.identifyingcode.trim(),
                    phonenumber: formData.phonenumber.trim(),
                },
                success: function (data, status, xhr) {
                    if (data.errorMessage) {
                        myApp.alert(data.errorMessage);
                    } else {
                        myApp.alert('注册成功',function (e) {
                            mainView.router.load({
                                url:'usercenter',
                                reload:true
                            })
                        });
                    }
                }
            });
        });
    });
    myApp.onPageInit('collection',function (page) {
        var movieItems = [];
        var cinemaItems = [];
        var albumItems = [];
        var movieList = myApp.virtualList($$('#tab-collection-movie .virtual-list'), {
            items: movieItems,
            template: movieListTemplate,
            height: 124
        });
        var cinemaList = myApp.virtualList($$('#tab-collection-cinema .virtual-list'), {
            items: cinemaItems,
            template: cinemaListTemplate,
            height: 100
        });
        var albumList = myApp.virtualList($$('#tab-collection-album .virtual-list'), {
            items: albumItems,
            template: collectionAlbumTemplate,
            height: 191
        });

        var req = {
            type: 0,
            pageMovie: 0,
            pageCinema: 0,
            pageAlbum: 0,
        };

        $$('#tab-collection-movie').on('show', function () {
            req.type = 0;
            if (req.pageMovie == 0) {
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-movie.infinite-scroll'));
                        $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-movie.infinite-scroll'));
                            $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        movieList.appendItems(data.collection);
                        req.pageMovie++;
                    }
                });
            }
            $$('#tab-collection-movie.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-movie.infinite-scroll'));
                        $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-movie.infinite-scroll'));
                            $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        movieList.appendItems(data.collection);
                        req.pageMovie++;
                    }
                    loading = false;
                });
            })


        });
        $$('#tab-collection-cinema').on('show', function () {
            req.type = 1;
            // req.lat = localStorage.getItem('lat');
            req.lat = latitude;
            // req.lng = localStorage.getItem('lng');
            req.lng = longitude;
            if (req.pageCinema == 0) {
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-cinema.infinite-scroll'));
                        $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-cinema.infinite-scroll'));
                            $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        cinemaList.appendItems(data.collection);
                        req.pageCinema++;
                    }
                });
            }
            $$('#tab-collection-cinema.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-cinema.infinite-scroll'));
                        $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-cinema.infinite-scroll'));
                            $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        cinemaList.appendItems(data.collection);
                        req.pageCinema++;
                    }
                    loading = false;
                });
            })
        });
        $$('#tab-collection-album').on('show', function () {
            req.type = 2;
            if (req.pageAlbum == 0) {
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-album.infinite-scroll'));
                        $$( '#tab-collection-album  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-album  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-album.infinite-scroll'));
                            $$( '#tab-collection-album  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-album  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        albumList.appendItems(data.collection);
                        req.pageAlbum++;
                    }
                });
            }
            $$('#tab-collection-album.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getCollectionList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-collection-album.infinite-scroll'));
                        $$( '#tab-collection-album  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-collection-album  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.isLast) {
                            myApp.detachInfiniteScroll($$('#tab-collection-album.infinite-scroll'));
                            $$( '#tab-collection-album  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-collection-album  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        albumList.appendItems(data.collection);
                        req.pageAlbum++;
                    }
                    loading = false;
                });
            })
        });
        myApp.showTab('#tab-collection-movie');
    });
    myApp.onPageInit('footprint',function (page) {
        var movieItems = [];
        var cinemaItems = [];
        var movieList = myApp.virtualList($$('#tab-footprint-movie .virtual-list'), {
            items: movieItems,
            template: movieListTemplate,
            height: 124
        });
        var cinemaList = myApp.virtualList($$('#tab-footprint-cinema .virtual-list'), {
            items: cinemaItems,
            template: cinemaListTemplate,
            height: 100
        });

        var req = {
            type: 0,
            lastIndexMovie: 0,
            lastIndexCinema: 0,
        };
        $$('#tab-footprint-movie').on('show', function () {
            req.type = 0;
            // req.lat = localStorage.getItem('lat');
            req.lat = latitude;
            // req.lng = localStorage.getItem('lng');
            req.lng = longitude;
            if (req.lastIndexMovie == 0) {
                getFootprintList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-footprint-movie.infinite-scroll'));
                        $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.length <10) {
                            myApp.detachInfiniteScroll($$('#tab-footprint-movie.infinite-scroll'));
                            $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        movieList.appendItems(data);
                        req.lastIndexMovie = movieList.length;
                    }
                });
            }
            $$('#tab-footprint-movie.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getFootprintList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-footprint-movie.infinite-scroll'));
                        $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.length <10) {
                            myApp.detachInfiniteScroll($$('#tab-footprint-movie.infinite-scroll'));
                            $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-footprint-movie  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        movieList.appendItems(data);
                        req.lastIndexMovie = movieList.length;
                    }
                    loading = false;
                });
            })
        });
        $$('#tab-footprint-cinema').on('show', function () {
            req.type = 1;
            if (req.lastIndexCinema == 0) {
                getFootprintList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-footprint-cinema.infinite-scroll'));
                        $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.length <10) {
                            myApp.detachInfiniteScroll($$('#tab-footprint-cinema.infinite-scroll'));
                            $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        cinemaList.appendItems(data);
                        req.lastIndexCinema = cinemaList.length;
                    }
                });
            }
            $$('#tab-footprint-cinema.infinite-scroll').on('infinite', function (e) {
                if (loading) return;
                loading = true;
                getFootprintList(req,function (data) {
                    if (data.errorMessage) {
                        myApp.detachInfiniteScroll($$('#tab-footprint-cinema.infinite-scroll'));
                        $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                        $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                    } else {
                        if (data.length <10) {
                            myApp.detachInfiniteScroll($$('#tab-footprint-cinema.infinite-scroll'));
                            $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader').css('display', 'none');
                            $$( '#tab-footprint-cinema  .infinite-scroll-preloader .preloader-text').text('已全部显示');
                        }
                        cinemaList.appendItems(data);
                        req.lastIndexCinema = cinemaList.length;
                    }
                    loading = false;
                });
            })
        });
        myApp.showTab('#tab-footprint-movie');
    });

    var countdown = 60;
    var settime = function (obj) {
        if (countdown == 0) {
            obj.removeAttr("disabled");
            obj.text("获取验证码");
            countdown = 60;
            return;
        } else {
            obj.attr("disabled", true);
            obj.text("发送(" + countdown + ")");
            countdown--;
        }
        setTimeout(function () {
                settime(obj)
            }
            , 1000)
    };
    var phoneNumberCheck = function (p) {
        var str = /^1[34578]\d{9}$/;
        if (!str.test(p.trim())) {
            return false;
        } else {
            return true;
        }
    };
    var graphicCodeCheck = function (c) {
        if (c.trim() == '' || c.trim().length != 4) {
            return false;
        } else {
            return true;
        }
    };
    var identifyingCodeCheck = function (c) {
        if (c.trim() == '' || c.trim().length != 4) {
            return false;
        } else {
            return true;
        }
    };
    var loading = false;
    var region_search = null;
    var filtrate_type = 0;
    var intelligent_sort = 0;
    var page_home = 0;
    var cinemaItems = [];
    var cinemaListTemplate = '<li>' +
        '<a data-ignore-cache="true" href="cinemahome?cinema_code={{cinema_code}}&lat='+latitude+'&lng='+ longitude+'" class="item-content" style="color: inherit;">' +
        '<div class="item-media">' +
        '<img src="{{cinema_picture}}" width="80" height="80" onerror="onCinemaPosterError(this)">' +
        '</div>' +
        '<div class="item-inner">' +
        '<div class="item-title-row" style="padding-bottom: 5px">' +
        '<div class="item-title">{{cinema_name}}</div>' +
        '<div class="item-after">' +
        '{{#if tag_1}}<div class="chip bg-red" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">1</div></div>{{/if}}' +
        '{{#if tag_2}}<div class="chip bg-yellow" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">2</div></div>{{/if}}' +
        '{{#if tag_3}}<div class="chip bg-green" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">3</div></div>{{/if}}' +
        '{{#if tag_4}}<div class="chip bg-blue" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">4</div></div>{{/if}}' +
        '{{#if tag_5}}<div class="chip bg-orange" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">5</div></div>{{/if}}' +
        '{{#if tag_6}}<div class="chip bg-gray" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">6</div></div>{{/if}}' +
        '{{#if tag_7}}<div class="chip bg-purple" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">7</div></div>{{/if}}' +
        '{{#if tag_8}}<div class="chip bg-pink" style="height: 18px;line-height: 18px;font-size: 14px;margin-right: 2px"><div class="chip-label">8</div></div>{{/if}}' +
        '</div>' +
        '</div>' +
        '<div class="item-subtitle" style="padding: 3px 0">' +
        '<img src="{{formatDoughnut score}}" width="85">' +
        '<span style="display: inline-block;margin-left: 8px">{{formatPerCapita price}}</span>' +
        '</div>' +
        '<div class="item-subtitle color-gray" style="padding-top: 5px">' +
        '<span style="display: inline-block;">{{region_name}}</span>' +
        '<span style="display: inline-block;float: right">{{#if endtime}}{{endtime}}&nbsp来过{{else}}{{formatDistance distance}}{{/if}}</span>' +
        '</div>' +
        '</div>' +
        '</a>' +
        '</li>';
    var cinemaList = null;
    var movieListTemplate = '<li>' +
        '<a data-ignore-cache="true" href="moviehome?mid={{mid}}" class="item-content" style="color: inherit;">' +
        '<div class="item-media">' +
        '<img src="{{MOVIE_POSTER mid poster}}" width="70" height="105" onerror="onMoviePosterError(this)">' +
        '</div>' +
        '<div class="item-inner">' +
        '<div class="item-title-row">' +
        '<div class="item-title">{{movie_name}}</div>' +
        '<div class="slik-ribbon">{{formatMovieScore score}}</div>' +
        '</div>' +
        '<div class="item-subtitle">&nbsp</div>' +
        '<div class="item-subtitle">{{category}}</div>' +
        '<div class="item-subtitle" style="font-size: 14px; color: #8a8a8a">{{#if endtime}}{{endtime}}&nbsp&nbsp观看{{else}}{{publish}}&nbsp&nbsp上映{{/if}}</div>' +
        '</div>' +
        '</a>' +
        '</li>';
    var albumListTemplate = '<li>' +
        '<div class="album-list-inner">' +
        '<a data-ignore-cache="true" href="filtedmovies?mode=0&parameter={{album_id}}">' +
        // '<canvas id="canvas-{{album_id}}" style="width:100%;height: 187.5px"></canvas>' +
        '<div style="position: relative;z-index: 100;margin-bottom: 5px;">' +
        '<div style="position: inherit;text-align: center;font-size: 0;">' +
        '<img class="clip-polygon" src="{{ALBUM_POSTER album_id wx_poster}}" style="width:100%;height: 187.5px;" onerror="onAlbumPosterError(this)">' +
        '</div>' +
        '<div class="wx-chip">' +
        '<div class="wx-chip-label">{{album_name}}</div>' +
        '<i class="icon wx-icon-line"></i>' +
        '<div class="wx-chip-label wx-chip-label-small">{{movie_count}}部影片</div>' +
        '</div>' +
        '<a href="#" class="album-album-collection album_{{album_id}} button button-round button-fill {{#if collection_id}}color-gray{{else}}color-custom{{/if}}" >' +
        '{{#if collection_id}}已收藏{{else}}收藏{{/if}}' +
        '</a>' +
        '</div>' +
        '</a>' +
        '<div style="margin: 0 0.5vw;font-size:0">' +
        '<div class="swiper-container swiper-init swiper-movie">' +
        '<div class="swiper-wrapper">' +
        '{{#each movies}}' +
        '<div class="swiper-slide" style="text-align: center">' +
        '<a data-ignore-cache="true" href="moviehome?mid={{mid}}">' +
        '<img onerror="onMoviePosterError(this)" style="width:31.33vw;height: 47vw" src="{{MOVIE_POSTER mid poster}}">' +
        '</a>' +
        '<div class="album-movie-name">' +
        '{{movie_name}}' +
        '</div>' +
        '<a class="album-movie-collection movie_{{album_id}}_{{mid}}">' +
        '<img width="17px" height="16px" src="./img/{{#if collection_id}}wx-set_movie_collection_2.png{{else}}wx-set_movie_collection_1.png{{/if}}">' +
        '</a>' +
        '<div class="slik-ribbon">{{formatMovieScore score}}</div>' +
        '</div>' +
        '{{/each}}' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</div>' +
        '</li>';

    var collectionAlbumTemplate = '<li>' +
        '<a data-ignore-cache="true" href="filtedmovies?mode=0&parameter={{album_id}}">' +
        '<div style="position: inherit;text-align: center;margin-bottom: 5px">' +
        '<img src="{{ALBUM_POSTER album_id wx_poster}}" width="100%" height="185px" onerror="onAlbumPosterError(this)">' +
        '</div>' +
        '<div style="width:100%;position: absolute;top: 35px;text-align: center">' +
        '<div class="chip" style="font-size: 22px;height: 35px;"> ' +
        '<div class="chip-label">{{album_name}}</div>' +
        '</div>' +
        '</div>' +
        '</a>' +
        '</li>';
    var Filter = function () {
        var el = $$('#filter');
        if (el.length == 0)return;
        var c1, a1, f = -1, mask;
        mask = $$('.mask').length ? $$('.mask') : $$('<div class="mask"></div>');
        mask.css('height', '100vh');
        mask.hide();
        el.parent().prepend(mask);
        //$$('.page[data-page="recommendedcinemas"]').prepend(mask);
        mask.click(hideView);

        function hideView() {
            c1 && c1.hide();
            a1 && a1.removeClass('active');
            mask.hide();
            f = -1;
        }

        el.find('.s1').each(function (i) {
            $$(this).click(function () {
                if (f == i) {
                    hideView();
                } else {
                    c1 && c1.hide();
                    a1 && a1.removeClass('active');
                    c1 = $$(el.find('.s2')[i]);
                    c1.show();
                    a1 = $$(this);
                    a1.addClass('active');
                    mask.show();
                    f = i;
                }
            });
        });
        el.find('.l1').each(function () {
            var e = $$(this);
            var n = e.next();
            e.find("li").each(function (i) {
                var c = $$(this);
                c.click(function () {
                    e.find("li.active").removeClass('active');
                    n.find(".default").removeClass('default');
                    var c2 = $$(n.find('.l2')[i]);
                    c2.addClass('default');
                    var a2 = $$(this);
                    a2.addClass('active');
                });
            });
        });
        el.find('.l2 li').click(function () {
            var a3 = $$(this);
            a3.parents('ul.l2').find('.active').removeClass('active');
            a3.addClass('active');
        });

        el.find('.l3 li').click(function () {
            var t = $$(this);
            t.parents('ul.l3').find('.active').removeClass('active');
            t.addClass('active');
            var d = t.dataset();
            if (d.type == 'type') {
                filtrate_type = d.id;
                $$('.type-label').text(t.text());
            } else {
                intelligent_sort = d.id;
                $$('.sort-label').text(t.text());
            }
            page_home = 0;
            cinemaList.deleteAllItems();
            initScrollPreloader('.page[data-page="recommendedcinemas"]');
            getRecommendedCinemas();
            hideView();
        });

        el.find('.s3 li').click(function () {
            var t = $$(this);
            var d = t.dataset();
            $$('.region-label').text(t.text());

            if (d.firstId != 0) {
                if (d.secondId != 0) {
                    region_search = '|' + d.firstId + '|' + d.secondId + '|';
                } else {
                    region_search = '|' + d.firstId + '|';
                }
            } else {
                region_search = t.text();
            }
            page_home = 0;
            cinemaList.deleteAllItems();
            initScrollPreloader('.page[data-page="recommendedcinemas"]');
            getRecommendedCinemas();
            hideView();
        });
    };
    var setFilterRegion = function (data) {
        var typeItems = [{name: '不限', id: 0}, {name: '可预约', id: 1}, {name: '不可预约', id: 2}]
        var sortItems = [{name: '距离最近', id: 0}, {name: '价格由低到高', id: 1}, {name: '价格由高到低', id: 2}]

        if (data[0].id != 0) {
            if (data[0].secondregions[0].id != 0) {
                region_search = '|' + data[0].id + '|' + data[0].secondregions[0].id + '|';
            } else {
                region_search = '|' + data[0].id + '|';
            }
        } else {
            region_search = data[0].name;
        }

        // region_search = null;
        filtrate_type = 0;
        intelligent_sort = 0;
        page_home = 0;

        $$('.region-label').text(data[0].secondregions[0].name);
        $$('.type-label').text(typeItems[0].name);
        $$('.sort-label').text(sortItems[0].name);

        $$('.region-list.s2 ul.l1').empty();
        $$('.region-list.s2 .s3').empty();
        $$('.s2.sort-list ul.l3').empty();
        $$('.s2.type-list ul.l3').empty();

        for (var i = 0; i < data.length; i++) {
            var tmp = '';
            if (i == 0) {
                tmp = '<ul class="l2 default">';
                $$('.region-list.s2 ul.l1').append('<li class="active">' + data[i].name + '</li>');
            } else {
                tmp = '<ul class="l2">';
                $$('.region-list.s2 ul.l1').append('<li>' + data[i].name + '</li>');
            }
            for (var l = 0; l < data[i].secondregions.length; l++) {
                if (l==0 && i==0){
                    tmp += '<li class="active" data-first-id="' + data[i].id + '" data-second-id="' + data[i].secondregions[l].id + '">' + data[i].secondregions[l].name + '</li>';
                } else {
                    tmp += '<li data-first-id="' + data[i].id + '" data-second-id="' + data[i].secondregions[l].id + '">' + data[i].secondregions[l].name + '</li>';
                }
            }
            tmp += '</ul>';
            $$('.region-list.s2 .s3').append(tmp);
        }

        for (var i = 0; i < sortItems.length; i++) {
            if (i==0){
                $$('.s2.sort-list ul.l3').append('<li class="active" data-type="sort" data-id="' + sortItems[i].id + '">' + sortItems[i].name + '</li>');
            } else {
                $$('.s2.sort-list ul.l3').append('<li data-type="sort" data-id="' + sortItems[i].id + '">' + sortItems[i].name + '</li>');
            }

        }

        for (var i = 0; i < typeItems.length; i++) {
            if (i==0){
                $$('.s2.type-list ul.l3').append('<li class="active" data-type="type" data-id="' + typeItems[i].id + '">' + typeItems[i].name + '</li>');
            } else {
                $$('.s2.type-list ul.l3').append('<li data-type="type" data-id="' + typeItems[i].id + '">' + typeItems[i].name + '</li>');
            }
        }

        Filter();
        cinemaList.deleteAllItems();
        initScrollPreloader('.page[data-page="recommendedcinemas"]');
        getRecommendedCinemas();
    };
    var initScrollPreloader = function (className) {
        myApp.attachInfiniteScroll($$(className + '  .infinite-scroll'));
        $$(className + '  .infinite-scroll-preloader .preloader').css('display', 'inline-block');
        $$(className + '  .infinite-scroll-preloader .preloader-text').text('正在加载...');
    };
    var removeScrollPreloader = function (className) {
        myApp.detachInfiniteScroll($$(className + '  .infinite-scroll'));
        $$(className + '  .infinite-scroll-preloader .preloader').css('display', 'none');
        $$(className + '  .infinite-scroll-preloader .preloader-text').text('不要触碰我的底线');
    };
    var getRecommendedCinemas = function () {
        var data = {
            page: page_home,
            lat: latitude,
            lng: longitude,
            filtrate_type: filtrate_type,
            region_search: region_search,
            intelligent_sort: intelligent_sort
        };
        postRequest('getrecommendedcinemas', data, function (data) {
            if (data.errorMessage) {
                removeScrollPreloader('.page[data-page="recommendedcinemas"]');
            } else {
                if (data.isLast) {
                    removeScrollPreloader('.page[data-page="recommendedcinemas"]');
                }
                cinemaList.appendItems(data.cinemas);
                page_home++;
            }
            loading = false;
        });
    };
    var getRecommendedMovies = function (request, callback) {
        postRequest('getrecommendedmovies', request, function (data) {
            callback(data);
        });
    };
    var getFilterMovies = function (request, callback) {
        postRequest('getfiltedmovies', request, function (data) {
            callback(data);
        });
    };
    var getCityByCode = function (code, callback) {
        var data = {
            city_code: code
        };
        postRequest('getcitybycode', data, function (data) {
            callback(data);
        });
    };
    var getCityByLatLng = function (callback) {
        var data = {
            // lat: localStorage.getItem('lat'),
            lat: latitude,
            // lng: localStorage.getItem('lng')
            lng: longitude
        };
        postRequest('getcitybylatlng', data, function (data) {
            callback(data);
        });
    };
    var getRegionsByCity = function (id, callback) {
        var data = {
            cityid: id
        };
        postRequest('getregionoptions', data, function (data) {
            callback(data);
        });
    };
    var getFootprintList = function (parameter,callback) {
        postRequest('getfootprintlist',parameter,function (data) {
            callback(data);
        });
    };
    var getCollectionList = function (parameter,callback) {
        postRequest('getcollectionlist',parameter,function (data) {
            callback(data);
        });
    };
    var getBookingOrderList = function (paramter, callback) {
        postRequest('getbookingorders',paramter,function (data) {
            callback(data);
        })
    };
    Filter();
    myApp.init();
};





